// ============================================================================
// 类型守卫和验证工具
// ============================================================================

import { 
  TaskStatus, 
  TaskType, 
  LogLevel, 
  ExportFormat, 
  AppErrorType,
  WeiboLoginData,
  ScrapeTask,
  TaskLogEntry,
  TaskProgress,
  AppConfig,
  UserInfo,
  WeiboData
} from '../types'

/** 检查是否为有效的任务状态 */
export function isValidTaskStatus(status: any): status is TaskStatus {
  return typeof status === 'string' && 
    ['pending', 'running', 'completed', 'failed', 'cancelled'].includes(status)
}

/** 检查是否为有效的任务类型 */
export function isValidTaskType(type: any): type is TaskType {
  return typeof type === 'string' && 
    ['search', 'user', 'trending', 'comments', 'followers'].includes(type)
}

/** 检查是否为有效的日志级别 */
export function isValidLogLevel(level: any): level is LogLevel {
  return typeof level === 'string' && 
    ['debug', 'info', 'warn', 'error'].includes(level)
}

/** 检查是否为有效的导出格式 */
export function isValidExportFormat(format: any): format is ExportFormat {
  return typeof format === 'string' && 
    ['json', 'csv', 'xlsx'].includes(format)
}

/** 检查是否为有效的错误类型 */
export function isValidErrorType(type: any): type is AppErrorType {
  return typeof type === 'string' && 
    ['NETWORK_ERROR', 'AUTH_ERROR', 'VALIDATION_ERROR', 'DATABASE_ERROR', 'FILE_SYSTEM_ERROR', 'UNKNOWN_ERROR'].includes(type)
}

/** 检查是否为有效的用户信息 */
export function isValidUserInfo(obj: any): obj is UserInfo {
  return obj && 
    typeof obj === 'object' &&
    typeof obj.uid === 'string' &&
    typeof obj.nickname === 'string' &&
    typeof obj.avatar === 'string' &&
    typeof obj.isVip === 'boolean'
}

/** 检查是否为有效的登录数据 */
export function isValidWeiboLoginData(obj: any): obj is WeiboLoginData {
  return obj && 
    typeof obj === 'object' &&
    typeof obj.id === 'string' &&
    Array.isArray(obj.cookies) &&
    isValidUserInfo(obj.userInfo) &&
    typeof obj.timestamp === 'number' &&
    typeof obj.isValid === 'boolean'
}

/** 检查是否为有效的任务进度 */
export function isValidTaskProgress(obj: any): obj is TaskProgress {
  return obj && 
    typeof obj === 'object' &&
    typeof obj.current === 'number' &&
    typeof obj.total === 'number' &&
    typeof obj.percentage === 'number' &&
    typeof obj.stage === 'string' &&
    obj.current >= 0 &&
    obj.total >= 0 &&
    obj.percentage >= 0 &&
    obj.percentage <= 100
}

/** 检查是否为有效的任务日志条目 */
export function isValidTaskLogEntry(obj: any): obj is TaskLogEntry {
  return obj && 
    typeof obj === 'object' &&
    typeof obj.id === 'string' &&
    obj.timestamp instanceof Date &&
    isValidLogLevel(obj.level) &&
    typeof obj.message === 'string'
}

/** 检查是否为有效的爬取任务 */
export function isValidScrapeTask(obj: any): obj is ScrapeTask {
  return obj && 
    typeof obj === 'object' &&
    typeof obj.id === 'string' &&
    isValidTaskType(obj.type) &&
    typeof obj.params === 'object' &&
    isValidTaskStatus(obj.status) &&
    typeof obj.accountId === 'string' &&
    obj.createdAt instanceof Date
}

/** 检查是否为有效的微博数据 */
export function isValidWeiboData(obj: any): obj is WeiboData {
  return obj && 
    typeof obj === 'object' &&
    typeof obj.id === 'string' &&
    typeof obj.text === 'string' &&
    isValidUserInfo(obj.user) &&
    obj.createdAt instanceof Date
}

/** 检查对象是否包含必需的属性 */
export function hasRequiredProperties<T extends Record<string, any>>(
  obj: any, 
  requiredProps: (keyof T)[]
): obj is T {
  if (!obj || typeof obj !== 'object') {
    return false
  }
  
  return requiredProps.every(prop => prop in obj)
}

/** 检查字符串是否为有效的UUID */
export function isValidUUID(str: string): boolean {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
  return uuidRegex.test(str)
}

/** 检查字符串是否为有效的URL */
export function isValidURL(str: string): boolean {
  try {
    new URL(str)
    return true
  } catch {
    return false
  }
}

/** 检查字符串是否为有效的邮箱地址 */
export function isValidEmail(str: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(str)
}

/** 检查数字是否在指定范围内 */
export function isInRange(num: number, min: number, max: number): boolean {
  return num >= min && num <= max
}

/** 检查数组是否不为空 */
export function isNonEmptyArray<T>(arr: any): arr is T[] {
  return Array.isArray(arr) && arr.length > 0
}

/** 检查对象是否为空 */
export function isEmpty(obj: any): boolean {
  if (obj == null) return true
  if (Array.isArray(obj) || typeof obj === 'string') return obj.length === 0
  if (typeof obj === 'object') return Object.keys(obj).length === 0
  return false
}

/** 深度检查对象相等性 */
export function deepEqual(a: any, b: any): boolean {
  if (a === b) return true
  
  if (a == null || b == null) return false
  
  if (typeof a !== typeof b) return false
  
  if (typeof a !== 'object') return false
  
  if (Array.isArray(a) !== Array.isArray(b)) return false
  
  const keysA = Object.keys(a)
  const keysB = Object.keys(b)
  
  if (keysA.length !== keysB.length) return false
  
  for (const key of keysA) {
    if (!keysB.includes(key)) return false
    if (!deepEqual(a[key], b[key])) return false
  }
  
  return true
}

/** 安全的JSON解析 */
export function safeJsonParse<T = any>(str: string, defaultValue: T): T {
  try {
    return JSON.parse(str)
  } catch {
    return defaultValue
  }
}

/** 安全的JSON字符串化 */
export function safeJsonStringify(obj: any, defaultValue: string = '{}'): string {
  try {
    return JSON.stringify(obj)
  } catch {
    return defaultValue
  }
}
